import React, { useState, useEffect, useRef } from 'react';
import { useLocation } from 'react-router-dom';
import { Toast, NavBar, Input, Button, FloatingPanel, Grid, Uploader, Divider, Image } from 'react-vant';
import { LocationO, StarO, CartO, Discount } from '@react-vant/icons'
import dayjs from 'dayjs';
import { useSelector } from 'react-redux';
import socket from '../../socket'
import { updateChat, getChat, sendImage } from '../../request'
import './chat.css'



const Chat = () => {
    const location = useLocation();
    // console.log('location',location);
    // 获取登录用户 一个普通对象
    const { currentUser } = useSelector(state => state.conter)
    // console.log('currentUser',currentUser);

    // 消息列表
    const [messages, setMessages] = useState([]);
    // 输入框的发送的内容
    const [inputValue, setInputValue] = useState('');
    // 目标用户是一个mongodb中的对象
    const [targetUser, setTargetUser] = useState({})
    // 聊天底部
    const messagesEndRef = useRef(null);

    // 定位到底部
    const scrollToBottom = () => {
        if (messagesEndRef.current) {
            // console.log(111);
            messagesEndRef.current.scrollTop = messagesEndRef.current.scrollHeight;
        }
    };

    // 加载聊天记录
    const loadChat = async () => {
        const params = {
            //sender：表示 消息的发送者  currentUser.username 是当前登录用户的用户名
            sender: currentUser.username,
            //接收者  如果这个接收者不存在的话就会使用这个发送者
            receiver: location.state.username ? location.state.username : currentUser.username,
        }
        console.log('params', params);
        let { data: { data, code } } = await getChat(params)
        // console.log(data);
        if (code == 200) {
            // console.log(data);
            setMessages(data.chatlist)
        }
    }

    // 挂载监听
    useEffect(() => {
        // 链接事件 心跳机制
        socket.on('connect', () => {
            setInterval(() => {
                if (socket.connected) {
                    socket.emit('ping');
                }
            }, 5000); // 每5秒发送一次心跳
        });

        // 向后端发送用户名生成链接对象
        socket.emit('join', { name: currentUser.username });

        // 自动回复事件监听
        socket.on('setId', data => {
            console.log(data, '系统反馈,自动回复');
        });

        // 监听接收到的消息
        socket.on('receiveMsg', async (data) => {
            // console.log("接受的消息", data);
            setTimeout(() => {
                loadChat()
            }, 1500)

            // console.log("加载消息");
        });
        socket.on('receiveImage', () => {
            // console.log('几首图片');
            setTimeout(() => {
                loadChat()
            }, 2000)
        })


        // 设置目标用户
        setTargetUser(location.state)
        console.log(location.state, '目标用户');
        
        loadChat()

        // 清理函数，用于在组件卸载时断开连接
        return () => {
            socket.disconnect();
        };
    }, []);

    // 到最新消息
    useEffect(() => {
        // 当组件挂载或消息更新时，滚动到底部
        scrollToBottom();
    }, [messages]);

    // 发送信息
    const sendMessage = async () => {
        // console.log('发送消息',targetUser.username);
        
        const obj = {
            sender: currentUser.username,
            receiver: targetUser.username,
            message: inputValue,
            time: dayjs().format('YYYY-MM-DD HH:mm:ss')
        }
        socket.emit('sendMsg', obj);
        await updateChat(obj)
        setTimeout(() => {
            loadChat()
        }, 500)
        setInputValue('');
    };

    // 图片
    const defaultValue = []
    const [imgBase, setImgBase] = useState('')


    // 发送图片
    const sendImg = async () => {
        const obj = {
            sender: currentUser.username,
            receiver: targetUser.username,
            message: imgBase,
            time: dayjs().format('YYYY-MM-DD HH:mm:ss')
        }
        socket.emit('sendImage', obj);
        await sendImage(obj)
        setTimeout(() => {
            loadChat()
        }, 500)
    }

    return (
        <div className='chat'>
            {/* 头部 */}
            <NavBar
                title={targetUser.username}
                leftText=''
                onClickLeft={() => Toast('返回')}
            />

            {/* 聊天内容 */}
            <div className='chatbox' ref={messagesEndRef}>
                {messages.map(item =>
                    <Divider
                        key={item.time}
                        contentPosition={item.receiver == targetUser.username ? 'right' : 'left'}>
                        <div className={item.receiver == targetUser.username ? 'my' : 'you'}>
                            <Image
                                width='30'
                                height='30'
                                src='https://img.yzcdn.cn/vant/cat.jpeg' />

                            <div className='receiver'>
                                <font>{item.receiver != targetUser.username ? item.sender : ''}</font>

                                {item.message.length > 50 ? <Image className='img' src={item.message} /> : <span>{item.message}</span>}

                            </div>
                        </div>
                    </Divider>
                )}
            </div>

            {/* 底部区域 */}
            <FloatingPanel anchors={[170, 320, window.innerHeight * 0.8]}>
                <div className='sendbox'>
                    <Input
                        type="text"
                        placeholder="输入消息"
                        value={inputValue}
                        clearable
                        clearTrigger="always"
                        onChange={(e) => setInputValue(e)} />
                    <Button type='info' onClick={sendMessage}>发送</Button>
                </div>
                {/* 输入框以下 */}
                <Grid gutter={8}>
                    <Uploader
                        accept='*'
                        defaultValue={defaultValue}
                        onChange={v => {
                            console.log(v)
                            if (v.length > 0) {
                                setImgBase(v[0].url)
                            }
                        }}
                    />
                    <Grid.Item icon={<LocationO />} onClick={() => 0} text='附近' />
                    <Grid.Item icon={<StarO />} onClick={() => 0} text='收藏' />

                    <Button onClick={sendImg}>发送图片</Button>

                </Grid>

            </FloatingPanel>
        </div>
    );
};

export default Chat;